<template>
  <div class="app-container">
    <el-row :gutter="10" class="row_container">
      <el-col class="left" :span="4">
        <!-- 左侧树结构 -->
        <el-card class="left-tree" style="height: 89vh">
          <!-- 在没有设置默认展开的时候需要设置
          :default-expanded-keys="[FirstId]"
            :current-node-key="FirstId"
            这两个属性
           -->
          <el-tree
            ref="tree"
            highlight-current
            icon-class="el-icon-folder"
            :data="departTree"
            :props="defaultProps"
            node-key="id"
            :default-expanded-keys="[FirstId]"
            :current-node-key="FirstId"
            class="filter-tree customer-tree-box"
            @current-change="selectNode"
          />
        </el-card>
      </el-col>
      <el-col class="right" :span="20">
        <el-main>
          <el-card style="height: 89vh" class="workArea_header">
            <!-- 全局map组件 -->
            <template #header>
              <span class="left_text">作业范围</span>
              <div :class="{ 'save-area-btn': true, disNone: isDisNone }">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="点击编辑释放绘制电子围栏功能"
                  placement="top"
                >
                  <el-button
                    v-show="isEdit === false"
                    class="rig_area_btn"
                    style="float: right"
                    type="primary"
                    @click="isEdit = true"
                  >
                    编辑
                  </el-button>
                </el-tooltip>

                <el-button
                  v-show="isEdit"
                  class="rig_area_btn"
                  style="float: right"
                  type="info"
                  @click="cancel"
                >
                  取消
                </el-button>
                <!-- TODO 添加el-tooltip -->
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="点击保存上传绘制好的电子围栏"
                  placement="top"
                >
                  <el-button
                    v-show="isEdit"
                    class="rig_area_btn"
                    style="float: right"
                    type="primary"
                    @click="sendPath"
                  >
                    提交
                  </el-button>
                </el-tooltip>

              </div>
            </template>
            <div class="keywords">
              地区关键词：
              <el-input
                v-model="input3"
                placeholder="请输入地址"
                class="input-with-select"
                @input="inputfz"
              />
            </div>
            <div v-show="isEdit" class="Edit">
              <el-button
                v-show="isOpenEdit === false"
                class="btn"
                type="primary"
                @click="startEdit"
              >开始绘制</el-button>
              <el-button
                v-show="isOpenEdit"
                class="btn"
                type="primary"
                @click="saveEdit"
              >完成绘制</el-button>
              <el-button
                v-show="isOpenEdit"
                class="btn"
                type="default"
                @click="delOutletsScope"
              >删除围栏</el-button>
              <p>
                <img
                  data-v-192cb3bb=""
                  src="/static/img/warn.3e9beae3.png"
                  alt=""
                  style="
                    width: 14px;
                    vertical-align: middle;
                    margin-bottom: 2px;
                    margin-right: 6px;
                  "
                >
                <span>点击或拖动鼠标绘制作业范围，右击鼠标结束图形绘制，图形不可有交叉点。完成绘制后，点击提交按钮保存。每个机构仅可支持绘制一个作业范围</span>
              </p>
            </div>
            <baidu-map
              :center="center"
              :zoom="zoom"
              class="bm-view"
              inertial-dragging
              :scroll-wheel-zoom="true"
              @ready="mapReady"
            >
              <bm-polygon
                :path="polygonPath"
                stroke-color="#ed9994"
                fill-color="#f2c8c5"
                stroke-style="dashed"
                :stroke-opacity="0.5"
                :stroke-weight="1"
                :editing="isEditing"
                @lineupdate="updatePolygonPath"
              />
              <!-- :path="polygonPath"
              stroke-color="blue"
              :stroke-opacity="0.5"
              :stroke-weight="2"
              :editing="true"
              @lineupdate="updatePolygonPath" -->
              <!-- 地区检索  keyword：关键字搜索   @searchcomplete：检索完成后的回调函数   auto-viewport：检索结束后是否自动调整地图事业  -->
              <bm-local-search
                style="display: none"
                :keyword="keyword"
                :auto-viewport="true"
                class="search"
              />
            </baidu-map>
            <!-- <Map
              ref="map"
              :keyword="keyword"
              :is-edit="isEdit"
              :polygon="polygonPath"
              :center="localPosition"
              :polygon-data="polygonData"
            /> -->
            <!--
              scroll-wheel-zoom是是否可以缩放
              @ready是图加载完后触发事件
              center是位置定位
              zoom是缩放大小限制
              inertial-dragging是允许惯性拖拽
            -->
            <!-- map位置 -->
          </el-card>
        </el-main>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 引入组件
import { getDepartTree, workScope, saveOutletsScope, delOutletsScope } from '@/api/base'
import { transListToTreeData } from '@/utils'
import { BaiduMap } from 'vue-baidu-map'
export default {
  name: 'WordAreaPage',
  // 需要引入的组件
  components: {
    BaiduMap
  },
  data() {
    return {
      // 动态控制class
      isDisNone: true,
      // 默认的props
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 是否进行编辑
      isEdit: false,
      center: {},
      zoom: 15,

      // 定位位置信息
      // 检索关键字
      keyword: '',
      // 输入框input值
      input3: '',
      departTree: [],
      currentNode: null,
      FirstId: '',
      // 覆盖路径currentNode
      polygonData: {},
      polygonPath: [],
      // 是否开始绘制,
      isOpenEdit: false,
      // 控制是否可以绘制
      isEditing: false
    }
  },
  async created() {
  },
  methods: {
    // 过滤器，过滤出空数据和不存在的数据
    // filterNode(value, data) {
    //   if (!value) return true
    //   return data.name.indexOf(value) !== -1
    // },
    // 获取tree 数据
    async getDepartTree() {
      this.departTree = transListToTreeData(
        JSON.parse(await getDepartTree()),
        '0'
      )
      // 选择第一个节点
      this.currentNode = this.selectFirstNode(this.departTree)

      this.FirstId = this.currentNode.id
      this.$nextTick(async() => {
        this.$refs.tree.setCurrentKey(this.currentNode) // 选中某个节点
        this.selectNode(this.currentNode)
      })
      // this.queryDetail() // 查询详情id
    },
    selectFirstNode(arr) {
      let node = null
      if (arr[0].children && arr[0].children.length) {
        node = this.selectFirstNode(arr[0].children)
      } else {
        node = arr[0]
      }
      return node
    },
    // 选中的某一项
    async selectNode(data) {
      // 切换位置 后 将地图编辑 和开始绘制状态变为false
      this.isOpenEdit = false
      this.isEditing = false
      this.isEdit = false
      // const currentLat = JSON.parse(data?.address)?.city.lat || data.latitude
      // const currentLng = JSON.parse(data?.address)?.city.lng || data.longitude
      // 当前地址的id
      // 拿到区域数据
      const res = await workScope({ id: data.id, type: 1 })
      console.log(res)
      const { center, zoom } = this.map.getViewport(res?.polygon?.map((item) => {
        return { lng: item.longitude, lat: item.latitude }
      }))
      this.zoom = zoom
      // 将数据进行处理
      this.polygonData = res
      if (res.polygon) {
        this.isDisNone = false
        this.polygonPath = res?.polygon.map((item) => {
          return { lng: item.longitude, lat: item.latitude }
        })
      } else {
        this.isDisNone = true
      }

      if (center.of) {
        this.center = { lat: res.latitude, lng: res.longitude }
      } else {
        this.center = center
      }
      this.currentNode = data
    },
    mapReady({ BMap, map }) {
      // 保存this指向，因为在百度的回调中this不指向vue
      // const _this = this
      // 获取自动定位方法
      this.map = map
      // const point = new BMapGL.Point(113.665, 34.784)
      // map.centerAndZoom(point, 15)
      // 获取自动定位获取的坐标信息
      this.getDepartTree()
      // const point = new BMap.Point(113.27, 23.13) // 选择一个经纬度作为中心点
      // map.centerAndZoom(point, 12) // 设置地图中心点和缩放级别
      // this.BMap = BMap
      // this.map = map
    },

    updatePolygonPath(e) {
      this.polygonPath = e.target.getPath()
    },
    // 开始绘制 打开绘制
    startEdit() {
      this.isOpenEdit = true
      this.isEditing = true
    },
    // 取消
    cancel() {
      this.isEdit = false
      this.isEditing = false
      this.isOpenEdit = false
    },
    // 删除围栏
    async delOutletsScope() {
      await delOutletsScope({
        id: +this.currentNode.id,
        type: 1
      })
      this.isOpenEdit = false
      this.$message.success('删除围栏成功')
    },
    // 地图绘制
    // 地图加载后的回调
    // 绘制面 (绘制完毕)
    saveEdit() {
      this.isEditing = false
      this.isOpenEdit = false
    },
    // 发送路径
    async sendPath() {
      try {
        this.polygonData.polygon = this.polygonPath.map((item) => {
          return { longitude: item.lng, latitude: item.lat }
        })
        const data = {
          ...this.polygonData
        }
        await saveOutletsScope(data)
        this.$message.success('完成绘制')
        this.cancel()
      } catch (err) {
        console.dir(err)
      }
    },
    // 输入框
    inputfz() {
      this.keyword = this.input3
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep
  .customer-tree-box
  > .el-tree-node
  > .el-tree-node__content
  .el-tree-node__expand-icon.is-leaf {
  width: 14px;
  height: 13px;
  background: url()
    no-repeat;
  background-size: 100% 100%;
}
::v-deep .el-tree-node__content > .el-tree-node__expand-icon::before {
  content: "";
}
::v-deep
  .customer-tree-box
  > .el-tree-node
  > .el-tree-node__content
  .el-tree-node__expand-icon:not(.is-leaf).expanded {
  transform: none !important;
  background: url()
    no-repeat;
  width: 14px;
  height: 13px;
  background-size: 100% 100%;
}
::v-deep
  .customer-tree-box
  > .el-tree-node
  > .el-tree-node__content
  .el-tree-node__expand-icon:not(.is-leaf) {
  background: url()
    no-repeat;
  width: 14px;
  height: 13px;
  background-size: 100% 100%;
}

::v-deep .customer-tree-box .el-tree-node__expand-icon:not(.is-leaf) {
  -webkit-transform: none !important;
  transform: none !important;
  background: url()
    no-repeat;
  width: 12px;
  height: 12px;
  background-size: 100% 100%;
}
::v-deep .customer-tree-box .el-tree-node__expand-icon:not(.is-leaf).expanded {
  -webkit-transform: none !important;
  transform: none !important;
  background: url()
    no-repeat;
  width: 12px;
  height: 12px;
  background-size: 100% 100%;
}
::v-deep .el-tree-node__label {
  margin-left: 8px;
}
/* el-card 头部阴影 */
.workArea_header {
  background-color: #fff;
}
.left {
  padding-top: 20px;
}
::v-deep .el-card__header {
  height: 60px;
  background: rgb(248, 250, 255) !important;
  display: flex;
  justify-content: space-between;
  .left_text {
    font-weight: 700;
  }
  align-items: center;
  ::v-deep .right {
    .save-area-btn {
      .rig_area_btn {
        display: block;
        background-color: #e15536;
        color: #fff;
        width: 90px;
        border-radius: 5px;
        font-weight: 400;
        border: 1px solid #e15536;
      }
    }
  }
}
.disNone {
  display: none;
}
::v-deep .el-tree-node__content:hover {
  background-color: transparent;
  color: #ff7a63 !important;
}
::v-deep
  .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  color: #ff7a63 !important;
  background-color: transparent;
  //节点的字体颜色
}
::v-deep .el-card__body {
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
  color: rgb(0, 0, 0);
  text-align: left;
  position: relative;
  .Edit {
    padding-top: 10px;
    height: 80px;
    position: absolute;
    width: 100%;
    z-index: 1;
    text-size-adjust: none;
    background: rgb(255, 255, 255);
    p {
      font-size: 12px;
      color: rgb(198, 126, 18);
      width: 100%;
      background: rgb(255, 245, 231);
      height: 30px;
      line-height: 30px;
      text-align: left;
      padding-left: 10px;
    }
  }
}
/* 给个宽高 */
.left-tree {
  padding: 10px;
}
.bm-view {
  width: 100%;
  height: 668px;
  overflow: hidden;
  display: flex;
  -webkit-box-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  align-items: center;
}
.input-with-select {
  width: 400px;
  margin-bottom: 5px;
}
.search {
  height: 300px;
  overflow: auto;
}
// 百度连接点样式
::v-deep .BMap_vectex {
  background-image: none;
  width: 6px;
  height: 6px;
  background-color: red;
  border-radius: 50%;
  text-align: center;
}
</style>
